package com.ec.vs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ec.common.domain.Result;
import com.ec.vs.entity.VsAppointment;
import com.ec.vs.mapper.VsMapper;
import com.ec.vs.service.VsService;
import com.ec.vs.vo.VsAppointmentVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class VsServiceImpl implements VsService {

    private final VsMapper vsMapper;

    @Override
    public Result<Object> findVisitAppointmentsByPage(int page, int size) {
        // 1. 创建 MyBatis-Plus 分页对象
        Page<VsAppointment> mpPage = new Page<>(page, size);

        // 2. 查询（按创建时间倒序，如需其他排序自行调整）
        Page<VsAppointment> resultPage = vsMapper.selectPage(
                mpPage,
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<VsAppointment>()
                        .orderByDesc("create_time")
        );

        // 3. 手动封装返回结构
        Map<String, Object> result = new HashMap<>();
        result.put("records", resultPage.getRecords()); // 当前页数据
        result.put("total", resultPage.getTotal());     // 总记录数
        result.put("page", (int) resultPage.getCurrent()); // 当前页码
        result.put("size", (int) resultPage.getSize());    // 每页条数

        return Result.ok(result);
    }

    @Override
    public int updateVisitAppointment(VsAppointment appointment) {
        // 检查状态更新是否符合业务规则
        if (appointment.getStatus() == 2) { // 取消状态
            return vsMapper.updateStatusToCanceled(appointment.getId());
        } else {
            return vsMapper.updateById(appointment);
        }
    }

    @Override
    public int cancelVisitAppointment(Long id) {
        return vsMapper.updateStatusToCanceled(id);
    }

    @Override
    public int saveVisitAppointment(VsAppointment appointment) {
        return vsMapper.insert(appointment);
    }

    @Override
    public VsAppointment findVisitAppointmentByUserId(Long userId) {
        return vsMapper.selectOne(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<VsAppointment>()
                        .eq("user_id", userId)
        );
    }

    // 检查给定日期内的预约总数是否超过 20 个
    public boolean checkTimeConflict(VsAppointmentVo appointmentVo) {
        int count = vsMapper.countAppointmentsByDate(appointmentVo.getTime());
        return count > 20;
    }

    // 检查用户是否已经在同一时间提交了不同类型的预约
    public boolean checkUserTimeConflict(VsAppointmentVo appointmentVo) {
        int count = vsMapper.countUserAppointmentsByDate(appointmentVo.getUserId(), appointmentVo.getTime());
        return count > 0;
    }

    // 检查用户在一天内提交的预约总数是否超过 2 次
    public boolean checkUserDailyLimit(VsAppointmentVo appointmentVo) {
        int count = vsMapper.countUserAppointmentsByDate(appointmentVo.getUserId(), appointmentVo.getTime());
        return count >= 2;
    }

    @Override
    public Result<Object> searchVisitAppointments(String name,
                                                  String mobile,
                                                  String elderName,
                                                  String status,
                                                  int page,
                                                  int size) {

        // 1. 分页对象
        Page<VsAppointment> mpPage = new Page<>(page, size);

        // 2. 动态条件
        LambdaQueryWrapper<VsAppointment> qw = Wrappers.lambdaQuery();
        qw.like(StringUtils.hasText(name), VsAppointment::getName, name)
                .like(StringUtils.hasText(mobile), VsAppointment::getMobile, mobile)
                .like(StringUtils.hasText(elderName), VsAppointment::getElderName, elderName) // 如果字段名不同请替换
                .orderByDesc(VsAppointment::getCreateTime);

        // 3. 状态多值
        if (StringUtils.hasText(status)) {
            List<Integer> statusList = Arrays.stream(status.split(","))
                    .map(Integer::valueOf)
                    .collect(Collectors.toList());
            qw.in(VsAppointment::getStatus, statusList);
        }

        // 4. 查询
        Page<VsAppointment> resultPage = vsMapper.selectPage(mpPage, qw);

        // 5. 封装返回
        Map<String, Object> result = new HashMap<>();
        result.put("records", resultPage.getRecords());
        result.put("total", resultPage.getTotal());
        result.put("page", (int) resultPage.getCurrent());
        result.put("size", (int) resultPage.getSize());
        return Result.ok(result);
    }

}